from django import views
from django.shortcuts import render, redirect, HttpResponse
from django.urls import reverse
from rbac import models
from rbac.forms.role import RoleModelForm


class Show(views.View):
    def get(self, request):
        role_list = models.Role.objects.all()
        return render(request, 'rbac/role.html', {'role_list': role_list})


class Add(views.View):
    def get(self, request):
        role_form = RoleModelForm()
        return render(request, 'rbac/change.html', {'my_form': role_form})

    def post(self, request):
        role_form = RoleModelForm(data=request.POST)
        if role_form.is_valid():
            role_form.save()
            return redirect(reverse('rbac_role_list'))
        else:
            return render(request, 'rbac/change.html', {'my_form': role_form})


class Edit(views.View):
    def get(self, request, rid):
        obj = models.Role.objects.filter(id=rid).first()
        if not obj:
            return HttpResponse('404 not found')

        role_form = RoleModelForm(instance=obj)
        return render(request, 'rbac/change.html', {'my_form': role_form})

    def post(self, request, rid):
        obj = models.Role.objects.filter(id=rid).first()
        role_form = RoleModelForm(instance=obj, data=request.POST)
        if role_form.is_valid():
            role_form.save()
            return redirect(reverse('rbac_role_list'))
        else:
            return render(request, 'rbac/change.html', {'my_form': role_form})


class Del(views.View):
    def get(self, request, rid):
        origin_url = reverse('rbac_role_list')
        return render(request, 'rbac/delete.html', {'cancel': origin_url})

    def post(self, request, rid):
        models.Role.objects.filter(id=rid).delete()
        origin_url = reverse('rbac_role_list')
        return redirect(origin_url)
